import asyncio
import json
import struct
import sys
from pathlib import Path

from swiftshadow.core.task_manager import TaskManager
from swiftshadow.models.database import db
from swiftshadow.models.task import DownloadTask


def get_message():
    raw_length = sys.stdin.buffer.read(4)
    if not raw_length:
        sys.exit(0)
    message_length = struct.unpack('=I', raw_length)[0]
    message = sys.stdin.buffer.read(message_length).decode('utf-8')
    return json.loads(message)


def send_message(message):
    encoded_message = json.dumps(message).encode('utf-8')
    sys.stdout.buffer.write(struct.pack('=I', len(encoded_message)) + encoded_message)
    sys.stdout.buffer.flush()


async def main_async():
    await db.initialize()
    manager = TaskManager()
    await manager.start()

    while True:
        message = get_message()
        if message.get('action') == 'download_url':
            url = message.get('url')
            if url:
                try:
                    # Determine filename from URL
                    filename = Path(url).name
                    if not filename or '.' not in filename:  # Basic check for valid filename
                        filename = "downloaded_file"

                    # Create a download task
                    task = DownloadTask(
                        url=url,
                        title=f"Download from {url}",
                        filename=filename,
                        save_path=str(Path("/tmp") / filename),
                        quality="best",  # Default quality
                    )
                    task_id = await manager.add_task(task)
                    response = {'success': True, 'message': f'Download task {task_id} added for: {url}'}
                    send_message(response)
                except Exception as e:
                    response = {'success': False, 'message': f'Failed to add download task: {e}'}
                    send_message(response)
            else:
                send_message({'success': False, 'message': 'URL not provided'})
        else:
            send_message({'success': False, 'message': 'Unknown action'})


if __name__ == '__main__':
    asyncio.run(main_async())
